# encoding = utf-8
import datetime

import pandas as pd

from application.logging import logger
from application.utils.CodeTimingUtil import CodeTimingUtil
from application.utils.MySQLUtils import MySQLUtils


@CodeTimingUtil(name="天气数据补齐[Temperature_Missing_value_database]")
def Temperature_Missing_value_database(area_code, station_data):
    """
    天气数据补全
    :param area_code:
    :param station_data:
    :return:
    """
    # 查询语句:查询实时天气数据:根据地区编码
    sql = f"SELECT * FROM public_basic_actual_weather WHERE area_code='{area_code}' ORDER BY uptime"
    logger.info(f"查询语句: {sql}")
    # 获取链接
    con = MySQLUtils.get_mysql_connection()
    # 查询数据
    df = pd.read_sql_query(sql=sql, con=con)
    # 打印数据
    logger.info(f"天气数据:\n {df}")
    # 数据筛选
    df = df[["area_code", "uptime", "temp_curr"]]
    logger.info(f"天气数据筛选:\n {df}")
    #
    average_outside_temper = []
    min_outside_temper = []
    max_outside_temper = []
    # for -> -----------------------------------------------------------------------------------------------------------
    for i in range(len(station_data)):
        # 开始时间,截止时间
        start = station_data.iloc[i]["collect_time"]
        end = start + datetime.timedelta(days=1)
        # logger.info(f"开始时间:{start},截止时间:{end}")

        # 筛选数据:大于指定时间
        weather = df[df["uptime"] >= start]
        # 筛选数据:小于指定时间
        weather = weather[weather["uptime"] <= end]

        # 打印数据:天气数据
        # logger.info(f"{start}->{end} 天气数据:\n {weather}")
        # logger.info(f"{start} -> {end} 天气数据: {len(weather)}")

        #
        if weather.empty:
            average_outside_temper.append("Nan")
            min_outside_temper.append("Nan")
            max_outside_temper.append("Nan")
            pass  # if <-
        else:  # else ->
            average_outside_temper.append(sum(list(weather['temp_curr'])) / len(weather))  # 平均室外温度
            min_outside_temper.append(min(list(weather["temp_curr"])))  # 最小室外温度
            max_outside_temper.append(max(list(weather["temp_curr"])))  # 最大室外温度
            pass  # else <-
        pass  # for <- -------------------------------------------------------------------------------------------------
    #
    # 补全数据
    station_data["average_outside_temper"] = average_outside_temper
    station_data["min_outside_temper"] = min_outside_temper
    station_data["max_outside_temper"] = max_outside_temper
    #
    # 过滤数据:最小室温数据!=Nan
    logger.info(f"数据补全[最小室温数据!=Nan][过滤前]: \n{station_data}")
    station_data = station_data[station_data["min_outside_temper"] != "Nan"]
    logger.info(f"数据补全[最小室温数据!=Nan][过滤后]: \n{station_data}")
    # 返回数据
    return station_data
    pass


pass

if __name__ == '__main__':
    station_data_ = pd.DataFrame({"collect_time": [pd.to_datetime("2020-01-01")]})
    Temperature_Missing_value_database(area_code="110106000000", station_data=station_data_)

    pass
